﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using System.Threading;

namespace Sunboxsoft.ASMS.Client.UI
{
    public partial class LaunchForm : Form
    {
        private Thread _thread = null;

        private IModule _module;

        public LaunchForm(IModule module)
        {
            InitializeComponent();

            _module = module;
            ctlProgressBarControl.Properties.Step = 1;
        }

        protected override void OnLoad(EventArgs e)
        {
            _thread = new Thread(Running);
            _thread.Start();

            base.OnLoad(e);
        
        }

        private void Running()
        {
            bool result = true;
            if (_module.Authenticate() == false)
            {
                this.Invoke(new Action(() =>
                {
                    if (_module.CreateAuthForm().ShowDialog() != System.Windows.Forms.DialogResult.OK)
                    {
                        result = false;
                    }
                }));
            }

            if (result)
            {
                result = _module.Load(UIContext.Current.ModuleRuntimeContext, new ModuleLoadingProgress((progress, message) =>
                {
                    this.BeginInvoke(new Action(() =>
                    {
                        ctlProgressBarControl.EditValue = (int)(ctlProgressBarControl.Properties.Maximum * progress);
                        ctlLabelText.Text = message;
                    }));
                }));
            }

            this.BeginInvoke(new Action<bool>(OnLaunchCompleted), result);
        }

        private void OnLaunchCompleted(bool isSuccess)
        {
            if (isSuccess)
            {
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                this.DialogResult = DialogResult.Cancel;
            }
        }
    }
}
